/*打印3的倍数*/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

/*创建互斥锁和条件变量*/
pthread_mutex_t mutex;
pthread_cond_t cond;

/*公共资源*/
int i = 1;

void* thread1(void* arg)
{
	while(i <= 30)
	{
		pthread_mutex_lock(&mutex);
		if(i%3 == 0)
			pthread_cond_broadcast(&cond);
		else
			printf("thread 1:%d\n",i);
		pthread_mutex_unlock(&mutex);
		usleep(50000);//50ms
		i++;
	}
	
	return NULL;
}

void* thread2(void* arg)
{
	while(i < 30)
	{
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex); 
		if (i%3 == 0)
			printf("thread 2:%d\n", i);
		pthread_mutex_unlock(&mutex);		
	}

	return NULL;
}

void* thread3(void* arg)
{
	while(i < 30)
	{
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex); 
		if (i%3 == 0)
			printf("thread 3:%d\n", i);
		pthread_mutex_unlock(&mutex);		
	}

	return NULL;
}

void* thread4(void* arg)
{
	while(i < 30)
	{
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex); 
		if (i%3 == 0)
			printf("thread 4:%d\n", i);
		pthread_mutex_unlock(&mutex);
	}

	return NULL;
}

int main()
{
	pthread_t tid1,tid2,tid3,tid4;
	/*初始化互斥锁和条件变量*/
	pthread_mutex_init(&mutex,NULL);
	pthread_cond_init(&cond,NULL);
	
	/*创建线程1、2、3、4*/
	pthread_create(&tid1,NULL,thread1,NULL);
	pthread_create(&tid2,NULL,thread2,NULL);
	pthread_create(&tid3,NULL,thread3,NULL);
	pthread_create(&tid4,NULL,thread4,NULL);
	
	/*等待子线程结束并回收*/
	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);
	pthread_join(tid3, NULL);
	pthread_join(tid4, NULL);
	
	/*销毁互斥锁和条件变量*/
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);

	return 0;
}

